import router from "./router"; //这里是路由器
import nprogress from "nprogress";
//@ts-ignore
import "nprogress/nprogress.css";

//安装仓库
import useUserStore from "./store/modules/users.ts";
import pinia from "./store";
import setting from "../setting.ts";
//获取仓库
const userStore = useUserStore(pinia);
router.beforeEach(async (to: any, from: any, next: any) => {
    document.title = setting.title + "-" + to.meta.title
    nprogress.start();
    const token = userStore.token;
    console.log("token" + token);
    if (token) {
        //判断是不是去login，如果是，不给他去
        if (to.path === "/login") {
            next({path: "/"});
        } else {
            //没有用户信息，去获取
            if (!userStore.username) {
                try {
                    await userStore.userInfo();
                } catch (err) {//获取不到么
                    await userStore.userLogout();//把用户信息清空
                    next({path: "/login", query: {redirect: to.path}});//跳到登录页，并携带查询参数
                }
            }
            next();
        }
    //没有token的家伙只能去登录
    } else {
        if (to.path === "/login") {//有自知之明，准了
            next();
        } else {
            next({path: "/login", query: {redirect: to.path}});//只准去登录
        }
    }
});

router.afterEach((to: any, from: any) => {
    nprogress.done();
});
